﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace BookManagement
{
    class dbHelper
    {
        //1、定义连接字符串
        static string strConn = "Data Source=.;Initial Catalog=BookManagement;Integrated Security=True";
        /// <summary>
        /// 用于查询的方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet GetData(string sql)
        {
            //3、创建适配器对象
            SqlDataAdapter da = new SqlDataAdapter(sql, strConn);
            //4、创建数据集对象
            DataSet ds = new DataSet();
            //5、将数据填充进数据集
            da.Fill(ds);
            return ds;
        }
        /// <summary>
        /// 用于增删改的方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static bool ExecuteNonQuery(string sql)
        {
            //3、创建连接对象
            SqlConnection conn = new SqlConnection(strConn);
            //4、创建command对象
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                //5、判断  判断当前数据库是否处于关闭状态
                if (conn.State == ConnectionState.Closed)
                {
                    //打开数据库
                    conn.Open();
                }
                return cmd.ExecuteNonQuery() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
    }
}
